package com.cupk.controllers;

import com.cupk.dtos.MessageResponse;
import com.cupk.services.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class FileController {

    private final FileService fileService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "category", defaultValue = "publication") String category,
            Authentication authentication) {
        
        String username = authentication.getName();
        log.info("文件上传请求，用户: {}, 文件: {}, 类别: {}", username, file.getOriginalFilename(), category);
        
        try {
            String fileUrl = fileService.uploadFile(file, category, username);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("fileUrl", fileUrl);
            response.put("fileName", file.getOriginalFilename());
            response.put("fileSize", file.getSize());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{category}/{filename:.+}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Resource> downloadFile(
            @PathVariable String category,
            @PathVariable String filename) {
        log.info("文件下载请求，分类: {}, 文件名: {}", category, filename);

        try {
            String fullPath = category + "/" + filename;
            Resource resource = fileService.loadFileAsResource(fullPath);
            String contentType = fileService.getContentType(filename);

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (Exception e) {
            log.error("文件下载失败", e);
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 在线预览文件
     */
    @GetMapping("/preview/{category}/{filename:.+}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Resource> previewFile(
            @PathVariable String category,
            @PathVariable String filename) {
        log.info("文件预览请求，分类: {}, 文件名: {}", category, filename);

        try {
            String fullPath = category + "/" + filename;
            Resource resource = fileService.loadFileAsResource(fullPath);
            String contentType = fileService.getContentType(filename);

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline")
                    .body(resource);
        } catch (Exception e) {
            log.error("文件预览失败", e);
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/{category}/{filename:.+}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<MessageResponse> deleteFile(
            @PathVariable String category,
            @PathVariable String filename,
            Authentication authentication) {

        String username = authentication.getName();
        log.info("文件删除请求，用户: {}, 分类: {}, 文件名: {}", username, category, filename);

        try {
            String fullPath = category + "/" + filename;
            fileService.deleteFile(fullPath, username);
            return ResponseEntity.ok(new MessageResponse("文件删除成功"));
        } catch (Exception e) {
            log.error("文件删除失败", e);
            return ResponseEntity.badRequest()
                    .body(new MessageResponse("文件删除失败: " + e.getMessage()));
        }
    }

    /**
     * 获取文件信息
     */
    @GetMapping("/info/{category}/{filename:.+}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Map<String, Object>> getFileInfo(
            @PathVariable String category,
            @PathVariable String filename) {
        log.info("获取文件信息请求，分类: {}, 文件名: {}", category, filename);

        try {
            String fullPath = category + "/" + filename;
            Map<String, Object> fileInfo = fileService.getFileInfo(fullPath);
            return ResponseEntity.ok(fileInfo);
        } catch (Exception e) {
            log.error("获取文件信息失败", e);
            return ResponseEntity.notFound().build();
        }
    }
}
